#include <iostream>
#include <string>
#include <cstdio>
#include <cstdlib> // getenv
#include <unistd.h> // gethostname chdir
#include <cstring>  // strlen strtok
#include <unistd.h> // execvp
#include <sys/types.h>
#include <sys/wait.h> // waitpid


#define COMMAND_SIZE 1024
#define FORMAT "%s@%s:~%s# "
			//					/home/whb/cplusplus/Linux.c++/myshell#
			// whb@hcss-ecs-6e86:~/cplusplus/Linux.c++/myshell$
  
// 1.命令行参数表
#define MAXARGC 128
char* g_argv[MAXARGC]; // Global variables 全局变量
int g_argc; 
	//int main(int argc, char *argv[], char *env[])

// 2.环境变量表
#define MAXENV 100
char* g_env[MAXENV];
int g_envs=0;

// for test
char cwd[1000];
char cwdenv[1000];

// last exit code
int lastcode = 0;

static std::string oldpwd;

const char* GetUserName()
{
	// char *getenv(const char *name);
	const char* username = getenv("USER");
	return username == NULL ? "None" : username;
}

const char* GetHostName()
{
	// Ubuntu 下无 HOSTNAME 环境变量
	// const char* hostname = getenv("HOSTNAME");	
    // return hostname == NULL ? "None" : hostname;
	
	static char hostname[50];
	int result = gethostname(hostname, sizeof(hostname));
    //if(result == 0) {
    //    printf("Hostname: %s\n", hostname);
    //} else {
    //    perror("gethostname");
    //}
	
	return result == 0 ? hostname : "None";
}

const char *GetPwd()
{
    //const char *pwd = getenv("PWD");
    const char *pwd = getcwd(cwd, sizeof(cwd));
    if(pwd != NULL)
    {
        snprintf(cwdenv, sizeof(cwdenv), "PWD=%s", cwd);
        putenv(cwdenv);
    }
    return pwd == NULL ? "None" : pwd;
}

const char* GetHome()
{
	const char* home = getenv("HOME");
	return home == NULL ? "" : home;
}

bool Cd()
{
	if(g_argc == 1)
	{
		std::string home=GetHome();
		if(home.empty()) 
			return true;
		oldpwd = GetPwd();
		chdir(home.c_str());
	}
	else
	{
		std::string where=g_argv[1];
		if(where == "~")
		{
			std::string home=GetHome();
			if(home.empty()) 
				return true;
			oldpwd = GetPwd();
			chdir(home.c_str());
		}
		else if(where == "-")
		{
			if(oldpwd.empty()) 
				return true;
			std::string pwd = GetPwd();
			chdir(oldpwd.c_str());
			oldpwd = pwd;
		}
		else
		{
			oldpwd=GetPwd();
			chdir(where.c_str());
		}
	}
	return true;
}

void Echo()
{
	// echo "hello world"
    // echo $?
    // echo $PATH
	if(g_argc == 2)
	{
		std::string opt = g_argv[1];
		if(opt == "$?")
		{
			std::cout << lastcode << std::endl;
            lastcode = 0;
		}
		else if(opt[0] == '$')
		{
			std::string name = opt.substr(1);
			char* env = getenv(name.c_str());
			if(env)
				std::cout<< env << std::endl;
		}
		else
		{
			std::cout<< opt <<std::endl;
		}
	}

}
void InitEnv()
{
	extern char **environ;
    memset(g_env, 0, sizeof(g_env));
    g_envs = 0;

	// 获取环境变量
	for(int i = 0; environ[i]; i++)
	{
		g_env[i] = (char*)malloc(strlen(environ[i]) + 1);
		strcpy(g_env[i],environ[i]);
		g_envs++;
	}
	g_env[g_envs]=NULL;
	
	// 导入环境变量
	for(int i = 0; g_env; i++)
	{
		putenv(g_env[i]);
	}
	environ = g_env;
}

const char* Split(const char* pwd)
{
	if(strcmp(pwd,"/") ==0)
		return "/";
	char *home = getenv("HOME");
	int n = strlen(home);

	if(strstr(pwd,home))
		return pwd+n;
	return pwd;
}

void MakeCommandPrompt(char *const cmd_prompt,int size)
{
	if(strcmp(Split(GetPwd()),GetPwd())==0)
		snprintf(cmd_prompt,size,"%s@%s:%s# ",GetUserName(),GetHostName(),Split(GetPwd()));
	else
		snprintf(cmd_prompt,size,FORMAT,GetUserName(),GetHostName(),Split(GetPwd()));
}

void PrintCommandPrompt()
{
	char prompt[COMMAND_SIZE];
	MakeCommandPrompt(prompt,sizeof(prompt));
	printf("%s", prompt);
	fflush(stdout);
}

bool GetCommandLine(char* out ,int size)
{
	char *c = fgets(out ,size ,stdin);
	if(c == NULL) return false;
	out[strlen(out)-1] = 0; // 处理最后的\n 
	if(strlen(out)==0) return false;
	return true;
}

// 3.命令行分析 "ls -l -a" -> "ls" "-l" "-a"
bool CommandParse(char* commandline)
{
#define separator " " // 分隔符
	g_argc = 0;

	for(g_argv[g_argc++]=strtok(commandline,separator);g_argv[g_argc]=strtok(nullptr,separator);g_argc++){};
	return g_argc > 0 ? true : false ;
}

void PrintArgvc()
{
	for(int i = 0;g_argv[i]; i++)
	{
		printf("g_argv[%d]:%s\n",i,g_argv[i]);
	}
	printf("%d\n",g_argc);
}

bool CheckAndExecBuiltin()
{
	std::string cmd = g_argv[0];
	if(cmd == "cd")
	{
		Cd();
		return true;
	}
	else if(cmd == "echo")
	{
		Echo();
		return true;
	}

	return false;
}

int Execute()
{
	pid_t id = fork();
	if(id == 0)
	{
		// 子进程
		execvp(g_argv[0],g_argv);
		exit(1);
	}

	int status = 0;
	pid_t rid = waitpid(id,nullptr,0);
	if(rid > 0)
    {
        lastcode = WEXITSTATUS(status);
    }
	return 0;
}

void Clean()
{
	for(int i = 0; g_env[i]; i++)
	{
		delete(g_env[i]);
	}
}

int main()
{
	// 初始化环境变量表
	InitEnv();

	while(1)
	{
	  // 1.输出命令行提示符
	  PrintCommandPrompt();
	
	  // 2.获取用户输入的命令
	  char commandline[COMMAND_SIZE];
	  if(!GetCommandLine(commandline,sizeof(commandline))) 
	  	continue;		
	  
	  // 3.命令行分析 "ls -l -a" -> "ls" "-l" "-a"
	  if(!CommandParse(commandline))
		  continue;
	  //PrintArgvc();
		
	  // 4.检查并处理内荐命令
	  if(CheckAndExecBuiltin())
		  continue;

	  // 5.执行命令
	  Execute();

	  // 6.释放资源
	  Clean();
	}
	return 0;
}
